package org.example.service.impl;

import com.alibaba.fastjson.JSON;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult;
import org.example.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liyishan
 * @date 2023/7/20 13:24
 * @apiNote
 */
@Service
public class TestServiceImpl implements TestService {


    @Autowired
    private RestTemplate restTemplate;
    @Value("${service-url.ddd-demo}")
    private String dddServiceUrl;


    @Override
    public String demo() {
        return restTemplate.getForObject(dddServiceUrl+"/test/demo",String.class);
    }

    @Override
    public String demo1(String name) {
        return restTemplate.getForObject(dddServiceUrl+"/test/demo1?name={1}",String.class,name);
    }

    @HystrixCommand
    @Override
    public List<String> demo1List(List<String> names) {
        System.out.println("getUserCache:" + JSON.toJSON(names));

        List<String> demoList = new ArrayList<>();
        for(String name:names){
            demoList.add(restTemplate.getForObject(dddServiceUrl+"/test/demo1?name={1}",String.class,name));
        }
        return demoList;
    }

    @CacheResult(cacheKeyMethod = "getCacheKey")
    @HystrixCommand(fallbackMethod = "getDefaultUser", commandKey = "getCacheKey")
    @Override
    public String test(String name) {
        System.out.println("getUserCache:"+ name);
        return restTemplate.getForObject(dddServiceUrl+"/test/demo1?name={1}",String.class,name);
    }

    public String getDefaultUser(String name){
        return name+"wait";
    }

    /**
     * 为缓存生成key的方法
     */
    public String getCacheKey(String name) {
        return name;
    }


    @HystrixCollapser(batchMethod = "demo1List",collapserProperties = {
            @HystrixProperty(name = "timerDelayInMilliseconds", value = "100")
    })
    @Override
    public String getFutrue(String name) {
        return restTemplate.getForObject(dddServiceUrl + "/test/demo1?name={1}", String.class, name);

    }
}
